import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routers'
import store from '../store';
import utils from '../utils'

// 调用 VueRouter
Vue.use(VueRouter);

////////创建 router 实例，然后传 routes 配置   history  ////////
const router = new VueRouter({
    // mode: 'hash',
    base: process.env.BASE_URL,
    routes // (缩写) 相当于 routes: routes
});

////////刷新页面更新动态路由////////
const menu = store.state.menus.menu;
if (menu.length) {
    // 获取动态路由
    const routes = utils.getRoutes(menu);
    // 添加动态路由
    router.options.routes = routes;
    //然后使用addRoutes 动态添加路由
    router.addRoutes(routes);
}


////////路由钩子函数路由之前////////
router.beforeEach((to, from, next) => {
    if (to.path === "/logout") {
        store.commit("menuReset");
        store.commit("tabsReset");
        next("/login");
    }
    const user = store.state.app.userInfo;
    if (!user && to.path !== "/login") {
        next("/login");
    } else {
        next();
    }
});

// const originalPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(location) {
//     return originalPush.call(this, location).catch(err => err)
// };

export default router;
